/**
 * MyServer.java create at Aug 30, 2011
 * author: weapon
 */
package dbms.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import dbms.Constants;
import dbms.Debug;

/**
 * @author weapon
 * 
 */
public class MyServer {
	public static void main(String args[]) {
		if (args.length != 1) {
			Debug.Error("no input database file");
		} else {
			DbmsServer.init(args[0]);

			try {
				ServerSocket server = null;
				Socket socket = null;
				try {
					server = new ServerSocket(Constants.DBMS_PORT);
					socket = server.accept();
					System.out.println("Client " + socket.getInetAddress() + " is coming.");
				} catch (Exception e) {
					System.out.println("Error." + e);
				}
				String line;
				BufferedReader is = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				PrintWriter os = new PrintWriter(socket.getOutputStream());

				
				line = is.readLine();
				System.out.println("Client:" + line);
				while (line != null) {
					String result = StartUp.dbmsServerExecute(line);
					if (result == null) {
						os.println("execute successfully.");
					} else {
						os.println(result);
					}
					os.flush();
					line = is.readLine();
					System.out.println("Client:" + line);
				}
				;
				os.close();
				is.close();
				socket.close();
				server.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
